package main

import (
	"log"
	"os"
	"ssr/common"
	"ssr/middleware"
	"ssr/routes"
	"strconv"

	"github.com/gin-gonic/gin"
)

func main() {

	// 1. 设置生产环境模式（根据环境变量自动判断）
	if os.Getenv("GIN_MODE") == "release" {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}
	r := gin.Default()

	// 2. 加载中间件

	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
		}
		c.Next()
	})
	r.Use(middleware.ResponseWrapper())
	r.Use(gin.Logger(), gin.Recovery())

	// 加载静态文件和模板
	common.LoadInitHTMLAndStatic(r)
	// 加载配置文件
	config := common.LoadingConfig()
	if config == nil {
		panic("Failed to load config")
	}
	// 注册路由
	routes.SetupRoutes(r)

	// 启动服务
	port := ":" + strconv.Itoa(config.APP.Port)
	if err := r.Run(port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
	// 捕获异常
	defer func() {
		if err := recover(); err != nil {
			log.Fatalf("Panic: %v", err)
		}
	}()
}
